package com.example.springboot.service.impl;
import cn.hutool.core.util.ObjectUtil;
import com.example.springboot.service.CartService;
import com.example.springboot.mapper.CartMapper;
import com.example.springboot.pojo.Cart;
import com.example.springboot.utils.ThreadLocalUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService{
    @Autowired
    private CartMapper cartMapper;

    @Override
    public void create(Cart cart) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("id");
        Cart dbCart = cartMapper.selectByUserIdAndGoodsId(userid, cart.getGoodsId());
        if (ObjectUtil.isNotEmpty(dbCart)) {
            dbCart.setGoodsnumber(dbCart.getGoodsnumber() + cart.getGoodsnumber());
            cartMapper.updateById(dbCart);
        } else {
            cart.setUserid(userid);
            cartMapper.create(cart);
        }
    }
    @Override
    public void delete(@RequestParam Integer id) {
        cartMapper.delete(id);
    }

    @Override
    public List<Cart> findByUserId() {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("id");
        return cartMapper.findByUserId(userid);
    }

    @Override
    public void updateById(Cart cart) {
        cartMapper.updateById(cart);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            cartMapper.delete(id);
        }
    }

    @Override
    public PageInfo<Cart> selectPage( Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
         Map<String,Object> map = ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("id");
        List<Cart> list = cartMapper.findByUserId(userid);
        return PageInfo.of(list);
    }

}
